package com.example.demo.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLIntegrityConstraintViolationException;

@ControllerAdvice(annotations = {RestController.class, Controller.class})//只要有这两个注解的都拦截
@Slf4j
@ResponseBody
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> sqlException(SQLIntegrityConstraintViolationException e){

        if (e.getMessage().contains("Duplicate entry")){
            String[] msg = e.getMessage().split(" ");
            log.info("该用户已存在:{}",msg[2]);
            return R.error("该用户已存在:"+msg[2]);
        }
        log.info("存数据出错：{}",e.getMessage());
        return R.error("未知错误");
    }
}
